package hot150;

// https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/?envType=study-plan-v2&envId=top-interview-150
public class q8 {

    public int maxProfit(int[] prices) {
        return method1(prices, prices.length);
    }

    /**
     * 贪心
     * 0 ms
     * 复杂度O(n)
     */
    public int method1(int[] prices, int n) {
        /*
            类似于爬山 例如 [1, 2, 3, 4]
            有盈利则买卖，买入1 卖出 2， 买入2 卖出3，每天的利润就是1 + 1 + 1， 等同于买入1卖出4
         */
        int mn = prices[0], mx = 0;
        int sum = 0;
        for (int i = 1; i < n; i++) {
            mn = Math.min(mn, prices[i]);
            mx = Math.max(mx, prices[i] - mn);
            if (mx > 0) {
                sum += mx;
                mn = prices[i];
                mx = 0;
            }
        }
        return sum;
    }

    public int method2(int[] prices, int n) {
        // 简化写法
        int sum = 0, mn = Integer.MAX_VALUE;
        for (int price : prices) {
            if (price > mn) {
                sum += price - mn;
            }
            mn = price;
        }
        return sum;
    }
}
